/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bashe.business.error;

import han.bashe.business.ejbclient.LogEjbClient;
import han.bashe.business.pipeline.Handler;
import han.bashe.business.pipeline.PipelineContext;
import han.bashe.common.dao.MessageDao;
import han.bashe.common.entity.BasheEntityConstants;
import han.bashe.common.entity.SoaConversation;
import han.bashe.common.exception.BasheErrorCode;
import han.bashe.common.exception.BasheException;
import han.bashe.common.message.RequestHelper;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @Author Kent
 */
public class ErrorHandler extends Handler {
	private static Log log = LogFactory.getLog(ErrorHandler.class);

	@Override
	public void postProcess(PipelineContext ctx) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean preProcess(PipelineContext ctx) {
		if (ctx.hasError())
			return true;
		return false;
	}

	@Override
	public void process(PipelineContext ctx) {

		try {
			Exception e = ctx.getError();
			BasheException be = null;
			log.error("Error handler process......");
			if (e instanceof BasheException) {
				be = (BasheException) e;

			} else {
				be = new BasheException(BasheErrorCode.UNKNOWN_ERROR,
						"unknown error ", e);
			}
			log.error("Error Code : " + be.getCode());
			log.error("Error Msg : " + be.getMsg());
			log.error("Error occur when processing message", e);
			RequestHelper rh = new RequestHelper(ctx.getRequest());
			String[] ids = LogEjbClient.getLog().logError(rh.getLogId(), ctx.getRequest(),
					ctx.getResponse(), be);
			if(rh.getConversationId() != null){
				SoaConversation con = MessageDao.findConversation(rh.getConversationId());
				con.setStatus(BasheEntityConstants.STATUS_ERROR);
				LogEjbClient.getLog().modifyConversation(con);
			}
			//handle retry error
			if(ctx.isRetry()){
				LogEjbClient.getLog().setRetryError(ctx.getRetryRecordId(), ids[1]);
			}
			
		} catch (Exception e) {

			log
					.error(
							"ErrorHandler.process() error : failed to log error info in db",
							e);
			ctx.setError(e);
		}

	}

}
